package cn.iune.erp.payment;

import java.math.BigDecimal;
import java.sql.Date;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.justep.baas.Utils;
import com.justep.baas.data.Row;
import com.justep.baas.data.RowState;
import com.justep.baas.data.Table;
import com.justep.baas.data.Transform;

import cn.iune.erp.setting.ISettingService;


@Transactional
@Service
public class AccountPaymentServiceImpl implements IAccountPaymentService {
	
	final static String PAYMENT_CLEARED = "cleared"; //已核销
	final static String PAYMENT_CLEARING = "clearing"; //部分核销
	final static String PAYMENT_UNCLEAR = "unclear"; //未核销
	final static String PAYMENT_CLEARED_LABEL = "已核销"; //已核销
	final static String PAYMENT_CLEARING_LABEL = "部分核销"; //部分核销
	final static String PAYMENT_UNCLEAR_LABEL = "未核销"; //未核销

	
	@Autowired
	private IAccountPaymentDao dao;
	@Autowired
	private IAccountPaymentDetailDao detailDao;
	
	@Autowired
	private ISettingService settingService;
	

	@Transactional
	@Override
	public void insert(AccountPayment a) {
		// TODO Auto-generated method stub
		dao.insert(a);
	}

	@Transactional
	@Override
	public void delete(String fID) {
		// TODO Auto-generated method stub
		dao.delete(fID);
	}
	
	@Transactional
	@Override
	public void update(AccountPayment a) {
		// TODO Auto-generated method stub
		dao.update(a);
	}

	@Override
	public AccountPayment getByID(String fID) {
		return dao.getByID(fID);
	}

	@Transactional

	@Override
	public JSONObject save(JSONObject object) throws ParseException  {
		System.out.println("save-->>"+object.toJSONString());
		// JSON转换Table
		Table table = Transform.jsonToTable(object);
		
		JSONObject data = new JSONObject();
		data.put("concept", table.getTableName());
		JSONArray rows = new JSONArray();
		List<String> idsNew = new ArrayList<String>();
		List<String> idsDel = new ArrayList<String>();
		
		List<Row> list = table.getRows();
		for(Row row : list){
			JSONObject javaObject= Transform.rowToJavaObject(table, row);
			AccountPayment obj = JSON.toJavaObject(javaObject, AccountPayment.class);
			if(RowState.NEW.equals(obj.getRowState())){
				dao.insert(obj);
				idsNew.add(obj.getfID());
			}
			if(RowState.DELETE.equals(obj.getRowState())){
				dao.delete(obj.getfID());
				idsDel.add(obj.getfID());
			}
			if(RowState.EDIT.equals(obj.getRowState())){
				AccountPayment objNew = dao.update(obj);
				//返回+1后的version到前台BizData中进行刷新，使得前台的version与后台的一致。
				///////////////////////////////////////////////////////////////////////
				JSONObject jsonRow = new JSONObject();
				jsonRow.put("id", obj.getfID());
				jsonRow.put("version", objNew.getVersion());
				rows.add(jsonRow);
				//////////////////////////////////////////////////////////////////////
			}
		}
		
		data.put("rows", rows);
		data.put("idsNew", idsNew);
		data.put("idsDel", idsDel);
		
		return data;
	}
	
	@Transactional
	@Override
	public JSONObject saveDetail(JSONObject object) throws ParseException {
		// TODO Auto-generated method stub
		// JSON转换Table
		Table table = Transform.jsonToTable(object);
		
		JSONObject json = new JSONObject();
		json.put("concept", table.getTableName());
		JSONArray rows = new JSONArray();
		
		List<Row> list = table.getRows();
		for(Row row : list){
			JSONObject javaObject= Transform.rowToJavaObject(table, row);
			AccountPaymentDetail obj = JSON.toJavaObject(javaObject, AccountPaymentDetail.class);
			if(RowState.NEW.equals(obj.getRowState())){
				detailDao.insert(obj);
			}
			if(RowState.DELETE.equals(obj.getRowState())){
				detailDao.delete(obj.getfID());
			}
			if(RowState.EDIT.equals(obj.getRowState())){
				AccountPaymentDetail objNew = detailDao.update(obj);
				JSONObject jsonRow = new JSONObject();
				jsonRow.put("id", obj.getfID());
				jsonRow.put("version", objNew.getVersion());
				rows.add(jsonRow);
			}
		}
		
		json.put("rows", rows);
		
		return json;
	}
	
	@Override
	public JSONObject querySimple(JSONObject param) {
		
		JSONObject json = new JSONObject();
		//获取物料档案（不包含SKU条目）
		JSONObject data;
		try {
			data = dao.querySimple(param);
		} catch (SQLException e) {
			e.printStackTrace();
			
			json.put("code", -1);
			json.put("status", e.getMessage());
			json.put("msg", "failure");
			
			return json;
		}
		
//		json.put("data", data);
//		json.put("code", 0);
//		json.put("msg", "success");
//		json.put("total", data.getBigInteger("total"));

		return data;		
	}
	

	//用于登记应收月档
	@Override
	public List<AccountPayment> getActualSKD(Date dateStart, Date dateEnd, String enterpriseNo) {
		return dao.getActualSKD(dateStart, dateEnd, enterpriseNo);
	}

	//用于登记应付月档
	@Override
	public List<AccountPayment> getActualFKD(Date dateStart, Date dateEnd, String enterpriseNo) {
		return dao.getActualFKD(dateStart, dateEnd, enterpriseNo);
	}

	//用于登记应收月档
	@Override
	public List<AccountPayment> getActualSKD(String customerID, Date dateStart, Date dateEnd, String enterpriseNo) {
		return dao.getActualSKD(customerID, dateStart, dateEnd, enterpriseNo);
	}

	//用于登记应付月档
	@Override
	public List<AccountPayment> getActualFKD(String customerID, Date dateStart, Date dateEnd, String enterpriseNo) {
		return dao.getActualFKD(customerID, dateStart, dateEnd, enterpriseNo);
	}

	
	@Transactional
	@Override
	public int confirm(AccountPayment a) {
		a.setState("confirm");
		a.setResultStatus("审核中");
		dao.update(a);
		return 0;
	}
	
	@Transactional
	@Override
	public int active(AccountPayment a) {
		a.setState("active");
		a.setResultStatus("待审核");
		dao.update(a);
		return 0;
	}
	
	@Transactional
	@Override
	public int confirm(String fID) {
		AccountPayment a = dao.getByID(fID);
		return this.confirm(a);
	}
	
	@Transactional
	@Override
	public int active(String fID) {
		AccountPayment a = dao.getByID(fID);
		return this.active(a);
	}
	
	@Transactional
	@Override
	public int open(String fID) {
		AccountPayment a = dao.getByID(fID);
		return this.open(a);
	}
	
	@Transactional
	@Override
	public int close(String fID) {
		AccountPayment a = dao.getByID(fID);
		return this.close(a);
	}
	
	@Transactional
	@Override
	public int open(AccountPayment a) {
		a.setStatus("open");
		dao.update(a);
		return 0;
	}
	
	@Transactional
	@Override
	public int close(AccountPayment a) {
		a.setStatus("close");
		dao.update(a);
		return 0;
	}

	@Transactional
	@Override
	public int agreeIt(String fID, String tUsercode, String tUsername, String userId) {
		AccountPayment a = dao.getByID(fID);
		// TODO Auto-generated method stub
		
		return this.agreeIt(a, tUsercode, tUsername, userId);
	}

	@Transactional
	@Override
	public int unAgree(String fID) {
		AccountPayment a = dao.getByID(fID);
		// TODO Auto-generated method stub
		
		return this.unAgree(a);
	}
	
	//审核通过，改变审核状态为confirm
	@Transactional
	@Override
	public int agreeIt(AccountPayment a, String tUsercode, String tUsername, String userId) {
		
		a.setAudit("confirm");
		a.setConfirmDate(Utils.getCurrentDate());
		a.setResultStatus("已审核");
		
		a.settUsercode(tUsercode);
		a.settUsername(tUsername);
		a.settDatetime(Utils.getCurrentDateTime());
		dao.update(a);
		
		return 0;
	}
	
	//审核拒绝，改变审核状态为active
	@Transactional
	@Override
	public int unAgree(AccountPayment a) {
		//判断是否可以撤销
		
		a.setAudit("active");
		a.setConfirmDate(null);
		a.setResultStatus("审核中");
		
		a.settUsercode(null);
		a.settUsername(null);
		a.settDatetime(null);
		dao.update(a);

		return 0;
	}	


	//打包主表（收付款单预收付款单主表）
	@Override
	public AccountPayment packing(
			String billType
			,String billTypeName 
			,String systemCode 
			,int flowType 
			,String revOpay 
			,int direction 
//			,String costingCode 
			,String autoCode 
			,String origin 
			,String originName 
			,String billNo 
			
			,String cUsercode//=com.justep.system.context.ContextHelper.getOperator().getCode();
			,String cUsername//=com.justep.system.context.ContextHelper.getOperator().getName();
			,String userId //= com.justep.system.context.ContextHelper.getOperator().getID();
			,String employeeNo 
			,String employeeName 
			,String enterpriseNo //= this.getEnterpriseNo();
			,String enterpriseName //= this.getEnterpriseName();
			){
		
		
		//SysInfo中记录的ID
//		final String APPID = "698decc4a8c6b4dae859d1aa4dc8d146";
		String APPID = null;
		
		if(billType.equals("SKDJ") || billType.equals("YSKD")){
			APPID = "698decc4a8c6b4dae859d1aa4dc8d146";
		}
		if(billType.equals("STDJ")){
			APPID = "b4c61069e396093477493c1d87934dd8";
		}
		
		if(billType.equals("FKDJ") || billType.equals("YFKD")){
			APPID = "d8fe20ea7486813eb66f9396a6576ba9";
		}
		if(billType.equals("FTDJ")){
			APPID = "ab358cdf19b548046dc6584c5929d867";
		}
		
		AccountPayment obj = new AccountPayment();
		String fID = Utils.getUUID();
		obj.setfID(fID);
		
		//单号
		/*
		Map<String,Object> map = usercenterService.getBillParam(billType, enterpriseNo);
		String billTypeName = (String) map.get("billTypeName");
//			String systemCode = (String) map.get("systemCode");
		int flowType = (int) map.get("flowType");
		String revOpay = (String) map.get("revOpay");
		int direction = (int) map.get("direction");
//			String costingCode = (String) map.get("costingCode");
		String autoCode = (String) map.get("autoCode");
		String origin = "WSSC";//(String) map.get("origin");
		String originName = "网上商城";//(String) map.get("originName");
		if("Y".equals(autoCode)){
			String billNo = (String) map.get("billNo");
			obj.setAccountPaymentNo(billNo);
			obj.setWriteOffNo(obj.getAccountPaymentNo());
		}
		*/
		if("Y".equals(autoCode)){
			obj.setAccountPaymentNo(billNo);
		}
		
		obj.setBillType(billType);
		obj.setBillTypeName(billTypeName);
		obj.setSystemCode(APPID);
		obj.setFlowType(flowType);
		obj.setRevOpay(revOpay);
		obj.setDirection(direction);
		obj.setOrigin(origin);
		obj.setOriginName(originName);
			
		
		obj.setState("active");
		obj.setStatus("open");
		obj.setAudit("active");
		obj.setOrderDate(Utils.getCurrentDate());
		
//		obj.setDealObject(fileCustomerService.getByID(customerID).getStorageTypeD());
//		obj.setDealObjectLabel(fileCustomerService.getByID(customerID).getStorageTypeDLabel());
//		obj.setCustomerID(customerID);
//		obj.setCustomerNo(fileCustomerService.getByID(customerID).getCustomerNo());
//		obj.setShortName(fileCustomerService.getByID(customerID).getShortName());
//		obj.setCustomerName(fileCustomerService.getByID(customerID).getCustomerName());
		
		
		obj.setOrderAmount(BigDecimal.ZERO);
		
		obj.setOrderAmountTotal(BigDecimal.ZERO);
		obj.setPendingAmount(BigDecimal.ZERO);
		obj.setDiscountCash(BigDecimal.ZERO);
		obj.setOrderAmountCleared(BigDecimal.ZERO);
		
//		obj.setAccountClearActual(BigDecimal.ZERO);
//		obj.setAccountClearPayable(BigDecimal.ZERO);
//		obj.setAccountDiscountCash(BigDecimal.ZERO);
		
		obj.setEmployeeNo(employeeNo);
		obj.setEmployeeName(employeeName);
		
		obj.setComments("来自商城");
		
		obj.setcUsercode(cUsercode);
		obj.setcUsername(cUsername);
		obj.setcDatetime(Utils.getCurrentDateTime());
		obj.setUserId(userId);
		obj.setEnterpriseNo(enterpriseNo);
		obj.setEnterpriseName(enterpriseName);

		obj.setVersion(0);
		
		return obj;
	}
	
	@Override
	public AccountPayment packing(
			String cUsercode//=com.justep.system.context.ContextHelper.getOperator().getCode();
			,String cUsername//=com.justep.system.context.ContextHelper.getOperator().getName();
			,String userId //= com.justep.system.context.ContextHelper.getOperator().getID();
			,String employeeNo 
			,String employeeName 
			,String enterpriseNo //= this.getEnterpriseNo();
			,String enterpriseName //= this.getEnterpriseName();
			){
		
		//SysInfo中记录的ID
//		final String APPID = "698decc4a8c6b4dae859d1aa4dc8d146";
		String APPID = null;
		
		AccountPayment obj = new AccountPayment();
		String fID = Utils.getUUID();
		obj.setfID(fID);
		
		obj.setSystemCode(APPID);
		//单号
		
		obj.setState("active");
		obj.setStatus("open");
		obj.setAudit("active");
		obj.setOrderDate(Utils.getCurrentDate());
		
		obj.setOrderAmount(BigDecimal.ZERO);
		
		obj.setPendingAmount(BigDecimal.ZERO);
		obj.setOrderAmountCleared(BigDecimal.ZERO);
		obj.setDiscountCash(BigDecimal.ZERO);
		obj.setOrderAmountCleared(BigDecimal.ZERO);
		
		obj.setOrderAmountTotal(BigDecimal.ZERO);
		
//		obj.setAccountClearPayable(BigDecimal.ZERO);
//		obj.setAccountClearActual(BigDecimal.ZERO);
//		obj.setAccountDiscountCash(BigDecimal.ZERO);

//		obj.setReceiveCashAmount(BigDecimal.ZERO);
//		obj.setGiveChangeAmount(BigDecimal.ZERO);
		
		obj.setEmployeeNo(employeeNo);
		obj.setEmployeeName(employeeName);
		
		obj.setcUsercode(cUsercode);
		obj.setcUsername(cUsername);
		obj.setcDatetime(Utils.getCurrentDateTime());
		obj.setUserId(userId);
		obj.setEnterpriseNo(enterpriseNo);
		obj.setEnterpriseName(enterpriseName);
//		
		obj.setVersion(0);
		
		return obj;
	}

	
	//插入预收款单
	@Transactional
	@Override
	public AccountPayment accountPaymentYSKDInsert(
			String guestNumber,
			
			String origin,
			String originName,
			String originNo,
			
			String dealObject,
			String dealObjectLabel,
			String customerID,
			String customerNo,
			String shortName,
			String customerName,
			
			String remark,
			
			BigDecimal orderAmount,
			
			String settleCategory,
			String settleCategoryLabel,
			String tradeNo,
			String orderNo,
			
			int flowType ,
			int cashSettle,
			
			String cUsercode,String cUsername,String userId,
			String employeeNo,String employeeName,
			
			String enterpriseNo,
			String enterpriseName

			){

		
		
		//获取会计科目（结算账户）的全路径信息
	//	AccountCaption accountCaption = accountCaptionService.getByID(captionID);
	//	String captionFullNo = null;// accountCaption.getCaptionFullNo();
	//	String captionFullName = null;// accountCaption.getCaptionFullName();
		String billType = "SKDJ";//用收款单的排序号
		
		Map<String,Object> map = settingService.getBillParam(billType, enterpriseNo);
		String billTypeName = (String) map.get("billTypeName");
		String systemCode = (String) map.get("systemCode");
//		int flowType = (int) map.get("flowType");
		String revOpay = (String) map.get("revOpay");
		int direction = (int) map.get("direction");
//		String costingCode = (String) map.get("costingCode");
		String autoCode = (String) map.get("autoCode");
//		String origin = (String) map.get("origin");
//		String originName = (String) map.get("originName");
		String billNo = (String) map.get("billNo");
		
		//打包主表AccountPayment
//		String billType = "SKDJ";//预付款单与付款单的序号进行大排序
//		AccountPayment accountPayment = this.packing(billType, cUsercode, cUsername, userId, employeeNo, employeeName, enterpriseNo, enterpriseName);
		AccountPayment accountPayment = this.packing(billType, billTypeName, systemCode, flowType, revOpay, direction, autoCode, origin, originName, billNo, cUsercode, cUsername, userId, employeeNo, employeeName, enterpriseNo, enterpriseName);
		
		///////////////////////////////////////////////////
//		accountPayment.setClearType("4");
//		accountPayment.setClearTypeLabel("4.预收款单");
		///////////////////////////////////////////////////
		
		accountPayment.setBillType("YSKD");//这么做是为了收款单使用相同的类型单号
		accountPayment.setBillTypeName("预收款单");
		
		accountPayment.setGuestNumber(guestNumber);
		
	//	int direction = accountPayment.getDirection();
	//	BigDecimal bgDirection = new BigDecimal(direction);
		
//		accountPayment.setState("confirm");
//		accountPayment.setAudit("confirm");
		
		accountPayment.setEmployeeNo(employeeNo);
		accountPayment.setEmployeeName(employeeName);
		
		accountPayment.setOrderNo(orderNo);
		
		accountPayment.setOrigin(origin);
		accountPayment.setOriginName(originName);
		accountPayment.setOriginNo(originNo);
		
		accountPayment.setDealObject(dealObject);
		accountPayment.setDealObjectLabel(dealObjectLabel);
		accountPayment.setCustomerID(customerID);
		accountPayment.setCustomerNo(customerNo);
		accountPayment.setShortName(shortName);
		accountPayment.setCustomerName(customerName);
		
		accountPayment.setRemark(remark);
		
		accountPayment.setSettleCategory(settleCategory);
		accountPayment.setSettleCategoryLabel(settleCategoryLabel);
		accountPayment.setSettleDate(Utils.getCurrentDate());
		accountPayment.setSettleCode(tradeNo);//结算号
		
		////////////////////////////////////////////////////////////////////////////////////////////
		
		accountPayment.setOrderAmount(orderAmount);//实收金额
		accountPayment.setDiscountCash(BigDecimal.ZERO);
		accountPayment.setOrderAmountTotal(accountPayment.getOrderAmount());
		accountPayment.setPendingAmount(accountPayment.getOrderAmount());
		
		//账
//		accountPayment.setAccountClearActual(accountPayment.getOrderAmountTotal());
		
		////////////////////////////////////////////////////////////////////////////////////////////
//		if(flowType!=null) {
//			accountPayment.setFlowType(Integer.parseInt(flowType));
//		}
		accountPayment.setCashSettle(cashSettle);
		
		//写入数据库主表
		dao.insert(accountPayment);
		
		return accountPayment;
	}
	
	//插入预收款单（会员余额充值）
	@Transactional
	@Override
	public AccountPayment accountPaymentYECZInsert(
			
			String origin,
			String originName,
			String originNo,
			
			String dealObject,
			String dealObjectLabel,
			String customerID,
			String customerNo,
			String shortName,
			String customerName,
			
			String remark,
			
			BigDecimal orderAmount,
			
			String settleCategory,
			String settleCategoryLabel,
			String tradeNo,
			String orderNo,
			
			int flowType ,
			int cashSettle,
			
			String cUsercode,String cUsername,String userId,
			String employeeNo,String employeeName,
			
			String enterpriseNo,
			String enterpriseName

			){

		
		
		//获取会计科目（结算账户）的全路径信息
	//	AccountCaption accountCaption = accountCaptionService.getByID(captionID);
	//	String captionFullNo = null;// accountCaption.getCaptionFullNo();
	//	String captionFullName = null;// accountCaption.getCaptionFullName();
		String billType = "SKDJ";//用收款单的排序号
		
		Map<String,Object> map = settingService.getBillParam(billType, enterpriseNo);
		String billTypeName = (String) map.get("billTypeName");
		String systemCode = (String) map.get("systemCode");
//		int flowType = (int) map.get("flowType");
		String revOpay = (String) map.get("revOpay");
		int direction = (int) map.get("direction");
//		String costingCode = (String) map.get("costingCode");
		String autoCode = (String) map.get("autoCode");
//		String origin = (String) map.get("origin");
//		String originName = (String) map.get("originName");
		String billNo = (String) map.get("billNo");
		
		//打包主表AccountPayment
//		String billType = "SKDJ";//预付款单与付款单的序号进行大排序
//		AccountPayment accountPayment = this.packing(billType, cUsercode, cUsername, userId, employeeNo, employeeName, enterpriseNo, enterpriseName);
		AccountPayment accountPayment = this.packing(billType, billTypeName, systemCode, flowType, revOpay, direction, autoCode, origin, originName, billNo, cUsercode, cUsername, userId, employeeNo, employeeName, enterpriseNo, enterpriseName);
		
		///////////////////////////////////////////////////
//		accountPayment.setClearType("Y");
//		accountPayment.setClearTypeLabel("Y.余额充值");
		///////////////////////////////////////////////////
		
		accountPayment.setBillType("YSKD");//这么做是为了收款单使用相同的类型单号
		accountPayment.setBillTypeName("预收款单");
		
//		accountPayment.setGuestNumber(guestNumber);
		
	//	int direction = accountPayment.getDirection();
	//	BigDecimal bgDirection = new BigDecimal(direction);
		
//		accountPayment.setState("confirm");
//		accountPayment.setAudit("confirm");
		
		accountPayment.setEmployeeNo(employeeNo);
		accountPayment.setEmployeeName(employeeName);
		
		accountPayment.setOrderNo(orderNo);
		
		accountPayment.setOrigin(origin);
		accountPayment.setOriginName(originName);
		accountPayment.setOriginNo(originNo);
		
		accountPayment.setDealObject(dealObject);
		accountPayment.setDealObjectLabel(dealObjectLabel);
		accountPayment.setCustomerID(customerID);
		accountPayment.setCustomerNo(customerNo);
		accountPayment.setShortName(shortName);
		accountPayment.setCustomerName(customerName);
		
		accountPayment.setRemark(remark);
		
		accountPayment.setSettleCategory(settleCategory);
		accountPayment.setSettleCategoryLabel(settleCategoryLabel);
		accountPayment.setSettleDate(Utils.getCurrentDate());
		accountPayment.setSettleCode(tradeNo);//结算号
		
		////////////////////////////////////////////////////////////////////////////////////////////
		
		accountPayment.setOrderAmount(orderAmount);//实收金额
		accountPayment.setDiscountCash(BigDecimal.ZERO);
		accountPayment.setOrderAmountTotal(accountPayment.getOrderAmount());
		accountPayment.setPendingAmount(accountPayment.getOrderAmount());
		
		//账
//		accountPayment.setAccountClearActual(accountPayment.getOrderAmountTotal());
		
		////////////////////////////////////////////////////////////////////////////////////////////
//		if(flowType!=null) {
//			accountPayment.setFlowType(Integer.parseInt(flowType));
//		}
		accountPayment.setCashSettle(cashSettle);
		
		//写入数据库主表
		dao.insert(accountPayment);
		
		return accountPayment;
	}


	//插入预收款单--代金券
	@Transactional
	@Override
	public AccountPayment accountPaymentRDJQInsert(
			
			String origin,
			String originName,
			String originNo,
			
			String dealObject,
			String dealObjectLabel,
			String customerID,
			String customerNo,
			String shortName,
			String customerName,
			
			String remark,
			
			BigDecimal orderAmount,
//			BigDecimal discountCash,
			
//			String settleCategory,
//			String settleCategoryLabel,
			String tradeNo,//代金券的编码
			String orderNo,
			
			String autoState/*提交*/,
			int flowType ,
			int cashSettle,
			
			String cUsercode,String cUsername,String userId,
			String employeeNo,String employeeName,
			
			String enterpriseNo,
			String enterpriseName

			){


		String settleCategory = "Q";
		String settleCategoryLabel = "Q.代金券";

		
		//获取会计科目（结算账户）的全路径信息
	//	AccountCaption accountCaption = accountCaptionService.getByID(captionID);
	//	String captionFullNo = null;// accountCaption.getCaptionFullNo();
	//	String captionFullName = null;// accountCaption.getCaptionFullName();
		String billType = "RDJQ";//用收款单的排序号
		
		Map<String,Object> map = settingService.getBillParam(billType, enterpriseNo);
		String billTypeName = (String) map.get("billTypeName");
		String systemCode = (String) map.get("systemCode");
//		int flowType = (int) map.get("flowType");
		String revOpay = (String) map.get("revOpay");
		int direction = (int) map.get("direction");
//		String costingCode = (String) map.get("costingCode");
		String autoCode = (String) map.get("autoCode");
//		String origin = (String) map.get("origin");
//		String originName = (String) map.get("originName");
		String billNo = (String) map.get("billNo");
		
		//打包主表AccountPayment
//		String billType = "SKDJ";//预付款单与付款单的序号进行大排序
//		AccountPayment accountPayment = this.packing(billType, cUsercode, cUsername, userId, employeeNo, employeeName, enterpriseNo, enterpriseName);
		AccountPayment accountPayment = this.packing(billType, billTypeName, systemCode, flowType, revOpay, direction, autoCode, origin, originName, billNo, cUsercode, cUsername, userId, employeeNo, employeeName, enterpriseNo, enterpriseName);
		
		accountPayment.setBillType("RDJQ");//这么做是为了收款单使用相同的类型单号
		accountPayment.setBillTypeName("代金券");
		
	//	accountPayment.setDirection(direction);
		
	//	int direction = accountPayment.getDirection();
	//	BigDecimal bgDirection = new BigDecimal(direction);
		
//		accountPayment.setState("confirm");
//		accountPayment.setAudit("confirm");
		
		accountPayment.setEmployeeNo(employeeNo);
		accountPayment.setEmployeeName(employeeName);
		
		accountPayment.setOrderNo(orderNo);
		
		accountPayment.setOrigin(origin);
		accountPayment.setOriginName(originName);
		accountPayment.setOriginNo(originNo);
		
		accountPayment.setDealObject(dealObject);
		accountPayment.setDealObjectLabel(dealObjectLabel);
		accountPayment.setCustomerID(customerID);
		accountPayment.setCustomerNo(customerNo);
		accountPayment.setShortName(shortName);
		accountPayment.setCustomerName(customerName);
		
		accountPayment.setRemark(remark);
		
		accountPayment.setSettleCategory(settleCategory);
		accountPayment.setSettleCategoryLabel(settleCategoryLabel);
		//accountPayment.setSettleDate(Utils.getCurrentDate());
		accountPayment.setSettleCode(tradeNo);//代金券号码
		
//		accountPayment.setSettleDate(predictStart);
//		accountPayment.setExpiringDate(predictEnd);
		
		////////////////////////////////////////////////////////////////////////////////////////////
		
		accountPayment.setOrderAmount(orderAmount);//实收金额
		accountPayment.setDiscountCash(BigDecimal.ZERO);//代金券的启用金额
		accountPayment.setOrderAmountTotal(accountPayment.getOrderAmount());
		accountPayment.setPendingAmount(accountPayment.getOrderAmount());
		
		//账
//		accountPayment.setAccountClearActual(accountPayment.getOrderAmountTotal());
		
		////////////////////////////////////////////////////////////////////////////////////////////
//		if(flowType!=null) {
//			accountPayment.setFlowType(Integer.parseInt(flowType));
//		}
		accountPayment.setCashSettle(cashSettle);
		
		//写入数据库主表
		dao.insert(accountPayment);
		
		return accountPayment;
	}

	
	
	
	
	
	//插入预付款单
	@Transactional
	@Override
	public AccountPayment accountPaymentYFKDInsert(
			String origin,
			String originName,
			String originNo,
			
			String dealObject,
			String dealObjectLabel,
			String customerID,
			String customerNo,
			String shortName,
			String customerName,
			
			String remark,
			
			BigDecimal orderAmount,
			
			String settleCategory,
			String settleCategoryLabel,
			String tradeNo,
			String orderNo,
			
			String autoState/*提交*/,
			int flowType ,
			int cashSettle,
			
			String cUsercode,String cUsername,String userId,
			String employeeNo,String employeeName,
			
			String enterpriseNo,
			String enterpriseName

			){

		
		
		//获取会计科目（结算账户）的全路径信息
	//	AccountCaption accountCaption = accountCaptionService.getByID(captionID);
	//	String captionFullNo = null;// accountCaption.getCaptionFullNo();
	//	String captionFullName = null;// accountCaption.getCaptionFullName();
		String billType = "FKDJ";//用付款单的排序号
		
		Map<String,Object> map = settingService.getBillParam(billType, enterpriseNo);
		String billTypeName = (String) map.get("billTypeName");
		String systemCode = (String) map.get("systemCode");
//		int flowType = (int) map.get("flowType");
		String revOpay = (String) map.get("revOpay");
		int direction = (int) map.get("direction");
//		String costingCode = (String) map.get("costingCode");
		String autoCode = (String) map.get("autoCode");
//		String origin = (String) map.get("origin");
//		String originName = (String) map.get("originName");
		String billNo = (String) map.get("billNo");
		
		//打包主表AccountPayment
//		String billType = "SKDJ";//预付款单与付款单的序号进行大排序
//		AccountPayment accountPayment = this.packing(billType, cUsercode, cUsername, userId, employeeNo, employeeName, enterpriseNo, enterpriseName);
		AccountPayment accountPayment = this.packing(billType, billTypeName, systemCode, flowType, revOpay, direction, autoCode, origin, originName, billNo, cUsercode, cUsername, userId, employeeNo, employeeName, enterpriseNo, enterpriseName);
	
		accountPayment.setBillType("YFKD");//这么做是为了收款单使用相同的类型单号
		accountPayment.setBillTypeName("预付款单");
		
	//	accountPayment.setDirection(direction);
		
	//	int direction = accountPayment.getDirection();
	//	BigDecimal bgDirection = new BigDecimal(direction);
		
		accountPayment.setState("confirm");
		accountPayment.setAudit("confirm");
		
		accountPayment.setEmployeeNo(employeeNo);
		accountPayment.setEmployeeName(employeeName);
		
		accountPayment.setOrderNo(orderNo);
		
		accountPayment.setOrigin(origin);
		accountPayment.setOriginName(originName);
		accountPayment.setOriginNo(originNo);
		
		accountPayment.setDealObject(dealObject);
		accountPayment.setDealObjectLabel(dealObjectLabel);
		accountPayment.setCustomerID(customerID);
		accountPayment.setCustomerNo(customerNo);
		accountPayment.setShortName(shortName);
		accountPayment.setCustomerName(customerName);
		
		accountPayment.setRemark(remark);
		
		accountPayment.setSettleCategory(settleCategory);
		accountPayment.setSettleCategoryLabel(settleCategoryLabel);
		accountPayment.setSettleDate(Utils.getCurrentDate());
		accountPayment.setSettleCode(tradeNo);//结算号
		
		////////////////////////////////////////////////////////////////////////////////////////////
		
		accountPayment.setOrderAmount(orderAmount);//实收金额
		accountPayment.setDiscountCash(BigDecimal.ZERO);
		accountPayment.setOrderAmountTotal(accountPayment.getOrderAmount());
		accountPayment.setPendingAmount(accountPayment.getOrderAmount());
		
		//账
		accountPayment.setPendingAmount(accountPayment.getOrderAmountTotal());
		
		////////////////////////////////////////////////////////////////////////////////////////////
//		if(flowType!=null) {
//			accountPayment.setFlowType(Integer.parseInt(flowType));
//		}
		accountPayment.setCashSettle(cashSettle);
		
		//写入数据库主表
		dao.insert(accountPayment);
		
		return accountPayment;
	}

	

	/*	
	@Override
    public void afterInsert(AccountPayment obj){
		//实收
		//////////////////////////////////////////////////////////////////////////////////////////
		//处理现结收款单
		if(obj.getBillType().equals("SKDJ") && "Y".equals(obj.getAutoPayment())){
			if (obj.getOrigin().equals("XSFP") && obj.getOriginNo()!=null && !"".equals(obj.getOriginNo())) {
				//
				String next, nextName, nextNo;
				next = obj.getBillType();
				nextName = obj.getBillTypeName();
				nextNo = obj.getAccountPaymentNo();
				accountPaymentService.updateNextNo(obj.getOriginNo(),obj.getEnterpriseNo(), next, nextName, nextNo);
			}
		}
		/////////////////////////////////////////////////////////////////////////////////////////////
		
		
	}
	
	@Override
    public void beforeDelete(String fID){
		AccountPayment obj = dao.getByID(fID);
		//实收
		//////////////////////////////////////////////////////////////////////////////////////////
		//处理现结收款单
		if(obj.getBillType().equals("SKDJ") && "Y".equals(obj.getAutoPayment())){
			if (obj.getOrigin().equals("XSFP") && obj.getOriginNo()!=null && !"".equals(obj.getOriginNo())) {
				//
				String next, nextName, nextNo;
				next = null;
				nextName = null;
				nextNo = null;
				accountPaymentService.updateNextNo(obj.getOriginNo(),obj.getEnterpriseNo(), next, nextName, nextNo);
			}
		}
		/////////////////////////////////////////////////////////////////////////////////////////////
		
	}
	*/
	
//	@Override
//	public AccountPayment getSKDJByNo(String accountPaymentNo, String enterpriseNo) {
//		return dao.getSKDJByNo(accountPaymentNo, enterpriseNo);
//	}

//	@Override
//	public AccountPayment getYSKDByNo(String accountPaymentNo, String enterpriseNo) {
//		// TODO Auto-generated method stub
//		return dao.getYSKDByNo(accountPaymentNo, enterpriseNo);
//	}

//	@Override
//	public AccountPayment getRDJQByNo(String accountPaymentNo, String enterpriseNo) {
//		return dao.getRDJQByNo(accountPaymentNo, enterpriseNo);
//	}

//	@Override
//	public AccountPayment getYFKDByNo(String accountPaymentNo, String enterpriseNo) {
//		// TODO Auto-generated method stub
//		return dao.getYFKDByNo(accountPaymentNo, enterpriseNo);
//	}

//	@Override
//	public AccountPayment getYSKDByOriginNo(String originNo, String enterpriseNo) {
//		// TODO Auto-generated method stub
//		return dao.getYSKDByOriginNo(originNo, enterpriseNo);
//	}


	//预收款单余额
//	@Override
//	public BigDecimal getUnclearYSKDAmount(String customerID, String enterpriseNo) {
//		return dao.getUnclearYSKDAmount(customerID, enterpriseNo);
//	}


	//获取未核销的预收款单列表（按照单据时间的从小到大排序）
	@Override
	public List<AccountPayment> getUnclearYSKDList(String guestNumber, String enterpriseNo) {
		return dao.getUnclearYSKDList(guestNumber, enterpriseNo);
	}
	
	@Override
	public List<AccountPayment> getUnclearYECZList(String customerID, String enterpriseNo) {
		return dao.getUnclearYECZList(customerID, enterpriseNo);
	}
	
	
	//更新预收款单核销金额
	@Override
	public int updateYSKDClearedAmount(String accountPaymentNo,String enterpriseNo, BigDecimal clearAmount){
		AccountPayment accountPayment = dao.getByNo(accountPaymentNo, enterpriseNo);
		
		//处理未核销金额
		accountPayment.setOrderAmountCleared(accountPayment.getOrderAmountCleared().add(clearAmount));
		accountPayment.setPendingAmount(accountPayment.getPendingAmount().subtract(clearAmount));
//		accountPayment.setAccountPending(accountPayment.getPendingAmount());
		
		if(accountPayment.getPendingAmount().compareTo(BigDecimal.ZERO)==0) {
			//票据余额<=0，已核销
			accountPayment.setHandling(PAYMENT_CLEARED);
			accountPayment.setHandlingLabel(PAYMENT_CLEARED_LABEL);
		}else if(accountPayment.getPendingAmount().compareTo(BigDecimal.ZERO)>0 && accountPayment.getPendingAmount().compareTo(accountPayment.getOrderAmount())<0) {
			//票据余额>0,并且票据余额<单据总额，部分核销
			accountPayment.setHandling(PAYMENT_CLEARING);
			accountPayment.setHandlingLabel(PAYMENT_CLEARING_LABEL);
		}else {
			//票据余额>=票据总额，未核销
			accountPayment.setHandling(PAYMENT_UNCLEAR);
			accountPayment.setHandlingLabel(PAYMENT_UNCLEAR_LABEL);
		}
		
//		accountPayment.setClearDatetime(Utils.getCurrentDateTime());
		
		dao.update(accountPayment);
		return 0;
	}
	
	
	//更新预收款单核销金额
	@Override
	public int updateRDJQClearedAmount(String accountPaymentNo,String enterpriseNo, BigDecimal clearAmount){
		AccountPayment accountPayment = dao.getByNo(accountPaymentNo, enterpriseNo);
		
		//处理未核销金额
		accountPayment.setOrderAmountCleared(accountPayment.getOrderAmountCleared().add(clearAmount));
		accountPayment.setPendingAmount(accountPayment.getPendingAmount().subtract(clearAmount));
//		accountPayment.setAccountPending(accountPayment.getPendingAmount());
		
		if(accountPayment.getPendingAmount().compareTo(BigDecimal.ZERO)==0) {
			//票据余额<=0，已核销
			accountPayment.setHandling(PAYMENT_CLEARED);
			accountPayment.setHandlingLabel(PAYMENT_CLEARED_LABEL);
		}else if(accountPayment.getPendingAmount().compareTo(BigDecimal.ZERO)>0 && accountPayment.getPendingAmount().compareTo(accountPayment.getOrderAmount())<0) {
			//票据余额>0,并且票据余额<单据总额，部分核销
			accountPayment.setHandling(PAYMENT_CLEARING);
			accountPayment.setHandlingLabel(PAYMENT_CLEARING_LABEL);
		}else {
			//票据余额>=票据总额，未核销
			accountPayment.setHandling(PAYMENT_UNCLEAR);
			accountPayment.setHandlingLabel(PAYMENT_UNCLEAR_LABEL);
		}
		
//		accountPayment.setClearDatetime(Utils.getCurrentDateTime());
		
		dao.update(accountPayment);
		return 0;
	}
	
	//更新预收款单核销金额
	@Override
	public int updateYFKDClearedAmount(String accountPaymentNo,String enterpriseNo, BigDecimal clearAmount){
		AccountPayment accountPayment = dao.getByNo(accountPaymentNo, enterpriseNo);
		
		//处理未核销金额
		accountPayment.setOrderAmountCleared(accountPayment.getOrderAmountCleared().add(clearAmount));
		accountPayment.setPendingAmount(accountPayment.getPendingAmount().subtract(clearAmount));
//		accountPayment.setAccountPending(accountPayment.getPendingAmount());
		
		if(accountPayment.getPendingAmount().compareTo(BigDecimal.ZERO)==0) {
			//票据余额<=0，已核销
			accountPayment.setHandling(PAYMENT_CLEARED);
			accountPayment.setHandlingLabel(PAYMENT_CLEARED_LABEL);
		}else if(accountPayment.getPendingAmount().compareTo(BigDecimal.ZERO)>0 && accountPayment.getPendingAmount().compareTo(accountPayment.getOrderAmount())<0) {
			//票据余额>0,并且票据余额<单据总额，部分核销
			accountPayment.setHandling(PAYMENT_CLEARING);
			accountPayment.setHandlingLabel(PAYMENT_CLEARING_LABEL);
		}else {
			//票据余额>=票据总额，未核销
			accountPayment.setHandling(PAYMENT_UNCLEAR);
			accountPayment.setHandlingLabel(PAYMENT_UNCLEAR_LABEL);
		}
		
//		accountPayment.setClearDatetime(Utils.getCurrentDateTime());
		
		dao.update(accountPayment);
		return 0;
	}
	
	
	//更新结算号和结算时间
	@Override
	public int updateSettleCode(String fID,String invoiceCode){
		AccountPayment accountPayment = dao.getByID(fID);
		if(accountPayment==null) return -1;
		accountPayment.setSettleCode(invoiceCode);
		
		dao.update(accountPayment);
		return 0;
	}
	
	//更新锁定（占用）代金券
	@Override
	public int updateOrigin(String fID,String origin, String originName, String originNo){
		AccountPayment accountPayment = dao.getByID(fID);
		if(accountPayment==null) return -1;
		accountPayment.setOrigin(origin);
		accountPayment.setOriginName(originName);
		accountPayment.setOriginNo(originNo);
		
		dao.update(accountPayment);
		return 0;
	}
	
	//更新结算号和结算时间
	@Override
	public int updateSettleCategory(AccountPayment accountPayment
			, String settleCategory, String settleCategoryLabel
			, String capitalID , String capitalNo , String capitalName, String capitalFullName 
			){
		accountPayment.setSettleCategory(settleCategory);
		accountPayment.setSettleCategoryLabel(settleCategoryLabel);
		accountPayment.setCapitalID(capitalID);
		accountPayment.setCapitalNo(capitalNo);
		accountPayment.setCapitalName(capitalName);
		accountPayment.setCapitalFullName(capitalFullName);
		
		dao.update(accountPayment);
		return 0;
	}
	
	
	//今日收款金额
	@Override
	public BigDecimal getRecAmountToday(List<Object> params) {
		return dao.getRecAmountToday(params);
		
	}
	
	//今日付款金额
	@Override
	public BigDecimal getPayAmountToday(List<Object> params) {
		return dao.getPayAmountToday(params);
		
	}
	
	@Override
	public JSONObject newData(JSONObject data) {
		return dao.create(data);
	}
	
	@Override
	public JSONObject deleteData(JSONObject param) {
		
		JSONArray ids = param.getJSONArray("ids");
		for(int i=0;i<ids.size();i++){
			String id = ids.getString(i);
			//这里可以增加是否可删除的判断
			
			//首先删除子表
			List<AccountPaymentDetail> sods = detailDao.getByMasterID(id);
			for(AccountPaymentDetail sod:sods){
				detailDao.delete(sod.getfID());
			}

			//然后删除主表
			dao.delete(id);
		}

		JSONObject data = new JSONObject();
		data.put("ids", ids);
		
		JSONObject json = new JSONObject();
		json.put("code", 0);
		json.put("msg", "success");
		json.put("data", data);
		
		return json;
	}
	
	@Override
	public JSONObject saveData(JSONObject param) {
		// TODO Auto-generated method stub
		JSONObject data;
		try {
			//保存主表
			data = this.save(param);
			
			//保存从表
			JSONArray slaves = param.getJSONArray("slaves");
			if(slaves.size()>0) {
				JSONObject slaveParam = slaves.getJSONObject(0);
				JSONObject slaveData = this.saveDetail(slaveParam);
				JSONArray slaveDatas = new JSONArray();
				slaveDatas.add(slaveData);
				data.put("slaves", slaveDatas);
			}
					
			JSONObject json = new JSONObject();
			json.put("code", 0);
			json.put("msg", "success");
			json.put("data", data);
			
			return json;
			
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
			JSONObject json = new JSONObject();
			json.put("code", -1);
			json.put("msg", e.getMessage());
			
			return json;
		} 
	}
	
	@Override
	public JSONObject queryData(JSONObject param) {
		// TODO Auto-generated method stub
		try {
			JSONObject jsonTable = dao.query(param);
			
			JSONObject json = new JSONObject();
			json.put("code", 0);
			json.put("msg", "success");
			json.put("data", jsonTable);
			
			return json;
		} catch (SQLException e) {
			e.printStackTrace();
			
			JSONObject json = new JSONObject();
			json.put("code", -1);
			json.put("msg", e.getMessage());
			return json;
		}
	}
	
	@Override
	public JSONObject validData(JSONObject param) {
		// TODO Auto-generated method stub
		return null;
	}

	//新增子表
	@Override
	public JSONObject newDataDetail(JSONObject data) {
		return detailDao.create(data);
	}
	
	//查询子表
	@Override
	public JSONObject queryDataDetail(JSONObject param) {
		// TODO Auto-generated method stub
		try {
			JSONObject jsonTable = detailDao.query(param);
			
			JSONObject json = new JSONObject();
			json.put("code", 0);
			json.put("msg", "success");
			json.put("data", jsonTable);
			
			return json;
		} catch (SQLException e) {
			e.printStackTrace();
			
			JSONObject json = new JSONObject();
			json.put("code", -1);
			json.put("msg", e.getMessage());
			return json;
		}
	}


		
}
